package com.by.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.by.entity.User;
import com.by.service.UserService;
import com.by.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 黄佳辉
 * @since 2023-01-04
 */
@RestController
@RequestMapping("/v1/user")
public class UserController {
    /**
     * 控制层依赖于业务层的接口  依赖抽象 不依赖具体实现 耦合度低
     */
    @Autowired
    UserService userService;


    @GetMapping("/query")
    public Result<Page<User>> query(Integer page, Integer pageSize){
        Page<User> userPage =userService.queryByPage(page, pageSize);
        return Result.success("查询用户列表",userPage);
    }


    @PostMapping("/save")
    public Result<String> save(@RequestBody User user){
        boolean saveFlag = userService.save(user);
        return saveFlag ? Result.success("保存成功") : Result.fail("保存失败");
    }

    @DeleteMapping("/delete/{id}")
    public Result<String> delete(@PathVariable String id){
        boolean deleteFlag = userService.removeById(id);
        return deleteFlag ? Result.success("删除成功") : Result.fail("删除失败");
    }

    @PutMapping("/update")
    public Result<String> update(@RequestBody User user){
        boolean updateFlag = userService.updateById(user);
        return updateFlag ? Result.success("修改成功") : Result.fail("修改失败");
    }

    @PostMapping("/login")
    public Result<User> login(@RequestBody User user){
        User loginResult=userService.login(user.getUsername(), user.getPassword());
        if(null == loginResult){
            return Result.fail("账号或密码错误");
        }

        //判断状态
        if(loginResult.getStatus()==2){
            return Result.fail("账号被锁定，请联系管理员");
        }

        //移除密码
        loginResult.setPassword(null);
        return Result.success("登录成功",loginResult);
    }
}
